package com.wzt.lianfirecontrol.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.adapter.BaseRecyclerAdapter;
import com.wzt.lianfirecontrol.adapter.home.system.jiance.SysJianCeDeviceAdapter;
import com.wzt.lianfirecontrol.adapter.utils.BarSelectAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.BarSelectModel;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongDeviceModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.SysDeviceModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.jiance.DeviceFloorModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.jiance.DeviceKindModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.jiance.DeviceStatusModel;
import com.wzt.lianfirecontrol.bean.recode.home.system.jiance.SystemBuildModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 首页监测系统点击可选状态类型楼层设备列表
 */
public class BarSelectFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener, SysJianCeDeviceAdapter.CallBack {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipe_container;
    private RecyclerView rlv_select_bar;
    private BarSelectAdapter barSelectAdapter;
    private View v_divider_line;
    private RecyclerView rlv_info_list;
    private LinearLayoutManager llm_info;
    private SysJianCeDeviceAdapter infoListAdapter;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int SELECT_FLOOR_WHAT = 0;
    private static final int DEVICE_STATUS_WHAT = 1;
    private static final int DEVICE_KIND_WHAT = 2;
    private static final int INFO_LIST_REQUEST_WHAT = 3;
    private static final int GET_VIDEO_LIST_WHAT = 4;

    private Dialog chooseFloorDialoag;

    private BarSelectModel[] barSelectModels = new BarSelectModel[3];
    private boolean[] requestStatus = new boolean[3];

    private boolean isShowCad = false;

    private SystemBuildModel systemBuildModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            if (null != bundle) {
                systemBuildModel = (SystemBuildModel) bundle.getSerializable("data");
            }
            if (null == systemBuildModel){
                activity.finish();
            }
            itemContentView = inflater.inflate(R.layout.f_bar_select, container, false);
            initView();
            for (int i = 0; i < requestStatus.length; i++){
                requestStatus[i] = false;
            }
            initSelectFloorHttpHelper();
            initDeviceStatusHttpHelper();
            initDeviceKindHttpHelper();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        swipe_container.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));
        
        initSelectBarView();

        initInfoListView();

        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        include_progress_bar.setVisibility(View.GONE);
        InitView.instance().initProgressBar(activity, include_progress_bar);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_no_data.setVisibility(View.GONE);

        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setVisibility(View.GONE);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
        ((ShowFragActivity)activity).setImageChangeAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowCad = !isShowCad;
                activity.finish();
            }
        });
    }



    private void initSelectBarView() {
        rlv_select_bar = itemContentView.findViewById(R.id.rlv_select_bar);
        v_divider_line = itemContentView.findViewById(R.id.v_divider_line);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rlv_select_bar.setLayoutManager(linearLayoutManager);
        barSelectAdapter = new BarSelectAdapter(activity);
        rlv_select_bar.setAdapter(barSelectAdapter);
        barSelectAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<BarSelectModel>() {
            @Override
            public void onItemClick(View v, int position, final BarSelectModel data) {
                String title = "";
                if (0 == position){
                    title = "选择楼层";
                }else if (1 == position){
                    title = "选择状态";
                }else if (2 == position){
                    title = "选择分类";
                }
                if (null != data.getSelectList() && data.getSelectList().size() > 0) {
                    chooseFloorDialoag = DialogUtils.getChooseListDialog(activity, data.getSelectList(), title, data.getCurrentPosition(), new BaseRecyclerAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View v, int position, Object object) {
                            data.setCurrentPosition(position);
                            data.setTitle(((BannerModel)object).getTitle());
                            DialogUtils.closeDialog(chooseFloorDialoag);
                            initInfoListHttpHelper();
                            barSelectAdapter.notifyDataSetChanged();
                        }
                    });
                    chooseFloorDialoag.show();
                }
            }
        });
    }

    private void initInfoListView() {
        rlv_info_list = itemContentView.findViewById(R.id.rlv_info_list);
        llm_info = new LinearLayoutManager(activity);
        llm_info.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_info_list.setLayoutManager(llm_info);
        infoListAdapter = new SysJianCeDeviceAdapter(activity, this);
        infoListAdapter.setNeedSetTopMargin(true);
        rlv_info_list.setAdapter(infoListAdapter);
        infoListAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<SysDeviceModel>() {
            @Override
            public void onItemClick(View v, int position, SysDeviceModel data) {
                Bundle skipToBundle = new Bundle();
                skipToBundle.putString("equId", data.getEquId());
                BannerModel bannerModel = new BannerModel();
                bannerModel.setActionType(ConstData.SHOWFRAG);
                bannerModel.setActionValue(ConstData.BAOJINGDETAIL);
                bannerModel.setActionTitle("详情");
                activity.setClickAction(bannerModel, skipToBundle);
            }
        });
    }

    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    /**
     * 获取列表
     */
    private void initSelectFloorHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        requestStatus[SELECT_FLOOR_WHAT] = true;
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", systemBuildModel.getBuildingId());

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new BarSelectListHttpHelper(activity, Url.DEVICE_FLOOR_URL,
                SELECT_FLOOR_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new BarSelectParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }
    /**
     * 设备状态
     */
    private void initDeviceStatusHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        requestStatus[DEVICE_STATUS_WHAT] = true;
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", systemBuildModel.getEquSysId());

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new BarSelectListHttpHelper(activity,  Url.DEVICE_STATUS_URL,
                DEVICE_STATUS_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new BarSelectParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }
    /**
     * 设备分类
     */
    private void initDeviceKindHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        requestStatus[DEVICE_KIND_WHAT] = true;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", systemBuildModel.getEquSysId());

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new BarSelectListHttpHelper(activity, Url.DEVICE_KIND_URL,
                DEVICE_KIND_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new BarSelectParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 获取列表
     */
    private void initInfoListHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("equSysId", systemBuildModel.getEquSysId());
        hashMap.put("buildingId", systemBuildModel.getBuildingId());
        if (null != barSelectModels[0] && null != barSelectModels[0].getSelectList() && barSelectModels[0].getSelectList().size() > 0) {
            hashMap.put("floorId", barSelectModels[0].getSelectList().get(barSelectModels[0].getCurrentPosition()).getId());
        }
        if (null != barSelectModels[1] && null != barSelectModels[1].getSelectList() && barSelectModels[1].getSelectList().size() > 0) {
            hashMap.put("runStatus", barSelectModels[1].getSelectList().get(barSelectModels[1].getCurrentPosition()).getStatusId());
        }
        if (null != barSelectModels[2] && null != barSelectModels[2].getSelectList() && barSelectModels[2].getSelectList().size() > 0) {
            hashMap.put("equTypeId", barSelectModels[2].getSelectList().get(barSelectModels[2].getCurrentPosition()).getId());
        }
        hashMap.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        Log.e("tga",JSONUtil.mapToJSonStr(hashMap).toString());
        HttpHelper homeListHttpHelper = new BarSelectListHttpHelper(activity, Url.SYS_BUILD_DEVICE_LIST_URL,
                INFO_LIST_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new BarSelectParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    /**
     * 设备分类
     */
    private void initVideoDeviceListHttpHelper(String videoIds) {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", videoIds);

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new BarSelectListHttpHelper(activity, Url.DEVICE_VIDEO_LIST_URL,
                GET_VIDEO_LIST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new BarSelectParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
        include_progress_bar.setVisibility(View.VISIBLE);
    }

    @Override
    public void getVideosList(String videoIds) {
        initVideoDeviceListHttpHelper(videoIds);
    }

    private class BarSelectListHttpHelper extends HttpHelper {

        public BarSelectListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class BarSelectParseJsonData extends ParseJsonData {

        public BarSelectParseJsonData() {
        }


        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what) {
                    case SELECT_FLOOR_WHAT:
                        LinkedList<DeviceFloorModel> deviceFloorModels = (LinkedList<DeviceFloorModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), DeviceFloorModel.class);
                        bundle.putSerializable("bar", deviceFloorModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case DEVICE_STATUS_WHAT:
                        LinkedList<DeviceStatusModel> deviceStatusModels = (LinkedList<DeviceStatusModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), DeviceStatusModel.class);
                        LinkedList<BannerModel> bannerModels = new LinkedList<>();
                        if (null != deviceStatusModels && deviceStatusModels.size() > 0){
                            for (int i = 0; i < deviceStatusModels.size(); i++){
                                BannerModel bannerModel = new BannerModel();
                                bannerModel.setTitle(deviceStatusModels.get(i).getName());
                                bannerModel.setStatusId(deviceStatusModels.get(i).getId());
                                bannerModels.add(bannerModel);
                            }
                        }
                        bundle.putSerializable("bar", bannerModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case DEVICE_KIND_WHAT:
                        LinkedList<DeviceKindModel> deviceKindModels = (LinkedList<DeviceKindModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), DeviceKindModel.class);
                        LinkedList<BannerModel> kindModels = new LinkedList<>();
                        if (null != deviceKindModels && deviceKindModels.size() > 0){
                            for (int i = 0; i < deviceKindModels.size(); i++){
                                BannerModel bannerModel = new BannerModel();
                                bannerModel.setTitle(deviceKindModels.get(i).getName());
                                bannerModel.setId(deviceKindModels.get(i).getId());
                                kindModels.add(bannerModel);
                            }
                        }
                        bundle.putSerializable("bar", kindModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case INFO_LIST_REQUEST_WHAT:
                        LinkedList<SysDeviceModel> deviceListModels = (LinkedList<SysDeviceModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(dataStr), SysDeviceModel.class);
                        bundle.putSerializable("list", deviceListModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case GET_VIDEO_LIST_WHAT:
                        LinkedList<JianKongDeviceModel> jianKongDeviceModels = (LinkedList<JianKongDeviceModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(dataStr), JianKongDeviceModel.class);
                        bundle.putSerializable("list", jianKongDeviceModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                }

            } catch(Exception e){
                e.printStackTrace();
                bundle.putBoolean(REQUEST_OK, false);
                bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
            }

        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            include_progress_bar.setVisibility(View.GONE);
            return;
        }
        switch (msg.what){
            case SELECT_FLOOR_WHAT:
            case DEVICE_STATUS_WHAT:
            case DEVICE_KIND_WHAT:
                setSelectBarData((LinkedList<BannerModel>) bundle.getSerializable("bar"), msg.what);
                break;
            case INFO_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setListData((LinkedList<SysDeviceModel>)bundle.getSerializable("list"));
                break;
            case GET_VIDEO_LIST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                LinkedList<JianKongDeviceModel> jianKongDeviceModels = (LinkedList<JianKongDeviceModel>) bundle.getSerializable("list");


                if (null != jianKongDeviceModels && jianKongDeviceModels.size() > 0){
                    if (jianKongDeviceModels.size() == 1){
                        Bundle skipToBundle = new Bundle();
                        skipToBundle.putSerializable("JianKongDeviceModel", jianKongDeviceModels.get(0));
                        activity.setClickAction(ConstData.VIDEO, jianKongDeviceModels.get(0).getAccessMode(), "监控设备", null, skipToBundle);

                    }else {
                        Bundle skipToBundle = new Bundle();
                        skipToBundle.putString(ConstData.SHOWTYPPE, ConstData.DEVICEVIDEOLIST);
                        skipToBundle.putSerializable("JianKongDeviceModels", jianKongDeviceModels);
                        activity.setClickAction(ConstData.SHOWFRAG, ConstData.INFOLIST, "监控设备", null, skipToBundle);
                    }
                }
                break;
        }
    }

    private void setSelectBarData(LinkedList<BannerModel> models, int what) {
        requestStatus[what] = false;
        if (null == barSelectModels[what]){
            barSelectModels[what] = new BarSelectModel();
        }
        if (null != models && models.size() > 0) {
            if (what != SELECT_FLOOR_WHAT) {
                BannerModel bannerModel = new BannerModel();
                bannerModel.setTitle("全部");
                bannerModel.setId("");
                bannerModel.setStatusId("");
                models.add(0, bannerModel);
            }
            barSelectModels[what].setSelectList(models);
        }
        switch (what){
            case SELECT_FLOOR_WHAT:
                barSelectModels[what].setTitle(barSelectModels[what].getSelectList().get(0).getTitle());
                break;
            case DEVICE_STATUS_WHAT:
                barSelectModels[what].setTitle("设备状态");
                break;
            case DEVICE_KIND_WHAT:
                barSelectModels[what].setTitle("设备分类");
                break;
        }

        if (isRequestOver()){
            if (isHasData()){
                rlv_select_bar.setVisibility(View.VISIBLE);
                v_divider_line.setVisibility(View.VISIBLE);
                List<BarSelectModel> barList = new ArrayList<>();
                for (int i = 0; i  < barSelectModels.length; i++){
                    if (null != barSelectModels[i]){
                        barList.add(barSelectModels[i]);
                    }
                }
                barSelectAdapter.clear();
                barSelectAdapter.addDatas(barList);
            }else {
                v_divider_line.setVisibility(View.GONE);
                rlv_select_bar.setVisibility(View.GONE);
            }
            initInfoListHttpHelper();
        }


    }

    private boolean isRequestOver(){
        for (int i = 0; i < requestStatus.length; i++){
            if (requestStatus[i]){
                return false;
            }
        }
        return true;
    }

    private boolean isHasData(){
        for (int i = 0; i < barSelectModels.length; i++){
            if (null != barSelectModels){
                return true;
            }
        }
        return false;
    }

    private void setListData(LinkedList<SysDeviceModel> list) {
        infoListAdapter.clear();
        if (null == list || list.size() == 0){
            include_no_data.setVisibility(View.VISIBLE);
            return;
        }
        include_no_data.setVisibility(View.GONE);
        infoListAdapter.addDatas(list);
    }

    @Override
    public void updateData() {
        super.updateData();
        initInfoListHttpHelper();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(chooseFloorDialoag);
    }
}
